# -*- coding: UTF-8 -*-

import time
import requests
import json
import sys,os
import configparser
import re

cf = configparser.ConfigParser()
cf.read(sys.path[0]+r"\notice.conf")
cur_time = int(time.time())

class WeChat:
    def __init__(self,corpid,agentid,secret):
        self.CORPID = corpid     #企业ID，在管理后台获取
        self.CORPSECRET = secret #自建应用的Secret，每个自建应用里都有单独的secret
        self.AGENTID = agentid   #应用ID，在后台应用中获取
        self.TOUSER = "@all"     #接收者用户名,多个用户用|分割,全部用户可使用@all

    def _get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        values = {'corpid': self.CORPID,
                  'corpsecret': self.CORPSECRET,
                  }
        req = requests.post(url, params=values)
        data = json.loads(req.text)
        return data["access_token"]

    def get_access_token(self):
        access_token = cf.get("system", "token")
        t = cf.get("system", "wxtm")
        
        if access_token:
            if 0 < cur_time - int(t) < 7260:
                return access_token
            else:
                access_token = self._get_access_token()
                cf.set("system","token",access_token)
                cf.set("system","wxtm",str(cur_time))
                cf.write(open(sys.path[0]+r"\notice.conf","w"))
                return access_token                   
        else:
            access_token = self._get_access_token()
            cf.set("system","token",access_token)
            cf.set("system","wxtm",str(cur_time))
            cf.write(open(sys.path[0]+r"\notice.conf","w"))
            return access_token

    def send_data(self, title,description):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "textcard",
            "agentid": self.AGENTID,
            "textcard": {
                "title": title,
                "description": description,
                "url":"http://imis.qq.com"
                }
            }
        send_msges=(bytes(json.dumps(send_values), 'utf-8'))
        respone = requests.post(send_url, send_msges)
        respone = respone.json()   #当返回的数据是json串的时候直接用.json即可将respone转换成字典
        return respone["errmsg"]
        
    def get_ip_info(self, ip):
        req = requests.get('http://ip.taobao.com/outGetIpInfo', params={'ip':ip,'accessKey':'alibaba-inc'})
        data = json.loads(req.text)["data"]
        return data["country"]+data["region"]+data["city"]+' ('+data["isp"]+')'

if __name__ == '__main__':
    f = os.popen('netstat -n -p tcp | find ":3389"')
    r = f.read()

    p = r'\:3389\s+?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\:'
    ipstr = re.findall(p,r)
    
    corpid = cf.get("config", "corpid")
    agentid = cf.get("config", "agentid")
    secret = cf.get("config", "secret")
    srv = cf.get("config", "srv")
    wx = WeChat(corpid,agentid,secret)
    
    if ipstr: #连接会话
        cf.set("system","ip",ipstr[0])
        cf.set("system","tm",str(cur_time))
        cf.write(open(sys.path[0]+r"\notice.conf","w"))
        
        desc = 'IP地址：{0}'\
               '\nIP归属：{1}'\
               '\n上线时间：{2}'.format(ipstr[0],wx.get_ip_info(ipstr[0]),time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))     
        
        wx.send_data(srv+" 服务器远程上线通知",desc)
    else: #断开会话
        tm = int(cf.get("system","tm"))
        desc = 'IP地址：{0}'\
               '\n上线时间：{1}'\
               '\n下线时间：{2}'\
               '\n总用时：{3} 分钟'.format(cf.get("system","ip"),time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(tm)),time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()),round((cur_time-tm)/60))     
        
        wx.send_data(srv+" 服务器远程下线通知",desc)